<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />
    
    <!-- 台账管理主容器 -->
    <div class="app-container">
      <!-- 顶部工具栏和主表格区域 -->
      <el-card shadow="hover" class="mb-20">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="分组名">
            <el-input
              v-model="queryParams.groupName"
              placeholder="请输入分组名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button type="success" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 主表格区域 -->
        <div class="table-wrapper">
          <el-table
            v-loading="loading"
            :data="tableData"
            stripe
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
                 <el-table-column type="index" width="50" />
            <el-table-column label="分组名" prop="groupName" width="300" align="center"/>
            <el-table-column label="可查看单位" align="center">
              <template #default="{row}">
                <el-popover
                  placement="bottom"
                  
                  trigger="hover"
                >
                  <template #reference>
                    <el-tag type="info" style="cursor: pointer;">
                      {{ row.viewableUnits.length > 0 ? row.viewableUnits.join(', ') : '无' }}
                    </el-tag>
                  </template>
                  <div style="max-width: 500px; max-height: 300px; overflow: auto;">
                    {{ row.viewableUnits.join(', ') }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <!-- 移除可查看表列，因为用户只要求显示分组名和单位 -->
            <el-table-column label="操作" align="center" width="200">
              <template #default="{row}">
                <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-show="total>0"
            :total="total"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @current-change="getList"
            @size-change="getList"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <edit-dialog
      v-if="dialogVisible"
      :title="dialogTitle"
      :form="form"
      :is-edit="isEdit"
      @confirm="submitForm"
      @close="dialogVisible = false"
      @get-list="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import database from '../../utils/database.js'
// 新增：根据export_id获取单条导出配置
const getExportConfigById = async (exportId) => {
  try {
    // 查询export表数据
    const exportResult = await database.query(
      'SELECT * FROM export WHERE export_id = ?',
      [exportId]
    );
    
    if (!exportResult || exportResult.length === 0) {
      throw new Error('未找到对应的导出配置');
    }
    
    const exportData = exportResult[0];
    
    // 获取所有单位信息（code和name的映射）
    const unitsMap = {};
    const unitsResult = await database.query('SELECT code, name FROM subUnits');
    unitsResult.forEach(unit => {
      unitsMap[unit.code] = unit.name;
    });
    
    // 获取可查看表数据
    const subtableResult = await database.query(
      'SELECT * FROM export_subtable WHERE export_id = ?',
      [exportId]
    );
    
    // 处理单位名称
    let viewableUnits = [];
    if (exportData.units) {
      const unitCodes = exportData.units.split(',');
      viewableUnits = unitCodes.map(code => ({
        value: code, // 保留原始code
        label: unitsMap[code] || code // 显示名称
      }));
    }
    
    // 处理可查看表数据
    const viewableTables = subtableResult.map(table => {
      // 获取表的所有列信息
      // 临时定义tableColumns，或者从EditDialog.vue导入
      const tableColumns = {
        'subUnits': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'code', comment: '单位编码' },
          { fieldName: 'name', comment: '单位名称' },
          { fieldName: 'status', comment: '状态' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'leader_personnel_infro': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'personnel_code', comment: '人员编码' },
          { fieldName: 'unit_name', comment: '单位名称' },
          { fieldName: 'department_name', comment: '部门名称' },
          { fieldName: 'name', comment: '姓名' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'birth_date', comment: '出生日期' },
          { fieldName: 'nationality', comment: '民族' },
          { fieldName: 'native_place', comment: '籍贯' },
          { fieldName: 'birth_place', comment: '出生地' },
          { fieldName: 'work_start_date', comment: '参加工作日期' },
          { fieldName: 'health_status', comment: '健康状况' },
          { fieldName: 'appointment_title', comment: '聘任职称' },
          { fieldName: 'education_level', comment: '学历' },
          { fieldName: 'graduate_school', comment: '毕业学校' },
          { fieldName: 'major_studied', comment: '所学专业' },
          { fieldName: 'study_type', comment: '学习类型' },
          { fieldName: 'current_position', comment: '现任行政职务' },
          { fieldName: 'position_level', comment: '职务级别' },
          { fieldName: 'graduation_date', comment: '毕业日期' },
          { fieldName: 'political_status', comment: '政治面貌' },
          { fieldName: 'id_card_number', comment: '身份证号' },
          { fieldName: 'resume', comment: '个人履历' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' },
          // { fieldName: 'created_by', comment: '创建人' },
          // { fieldName: 'updated_by', comment: '更新人' }
        ],
        'new_leader_report': [
          // { fieldName: 'id', comment: 'ID' },
          { fieldName: 'report_name', comment: '报告人姓名' },
          { fieldName: 'unit', comment: '单位' },
          { fieldName: 'position', comment: '职务' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'phone_number', comment: '手机号码' },
          { fieldName: 'id_number', comment: '身份证号' },
          { fieldName: 'political_status', comment: '政治面貌' },
          { fieldName: 'serious_illness', comment: '本人是否身患重大疾病' },
          { fieldName: 'marital_status', comment: '婚姻情况' },
          { fieldName: 'registered_address', comment: '户籍地具体地址' },
          { fieldName: 'passport_and_permits_info', comment: '本人取得普通护照、往来港澳通行证等情况' },
          { fieldName: 'overseas_social_media_info', comment: '本人因私设立使用国（境）外社交媒体账号情况' },
          { fieldName: 'children_international_marriage_info', comment: '子女与外国人、无国籍人、港澳台居民通婚的情况' },
          { fieldName: 'family_overseas_residency_info', comment: '配偶子女移居国（境）外等情况' },
          { fieldName: 'family_business_positions_info', comment: '配偶子女及其配偶受聘担任私营企业高级职务等情况' },
          { fieldName: 'legal_and_disciplinary_actions', comment: '本人配偶子女及其配偶被司法机关追究刑事责任等情况' },
          { fieldName: 'investigation_and_interrogation_info', comment: '本人涉嫌违规违纪违法犯罪问题等情况' },
          { fieldName: 'dishonest_person_status', comment: '本人或者配偶列为失信被执行人的情况' },
          { fieldName: 'relatives_basicInfro', comment: '亲属基本信息' },
          { fieldName: 'relatives_houseInfro', comment: '房产情况信息' },
          { fieldName: 'relatives_workin_railway', comment: '在铁路系统工作情况' },
          { fieldName: 'other_matters', comment: '其他需要报告的事项' },
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'problem_clues_situation': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'main_mark', comment: '主件标识' },
          { fieldName: 'is_unit', comment: '是否单位' },
          { fieldName: 'report_unit_name', comment: '填报单位名称' },
          { fieldName: 'report_unit_code', comment: '填报单位代码' },
          { fieldName: 'reflected_person', comment: '被反映人' },
          { fieldName: 'work_unit_and_position', comment: '工作单位及职务' },
          { fieldName: 'rank', comment: '职级' },
          { fieldName: 'handling_agency', comment: '办理机关' },
          { fieldName: 'main_problem_clue', comment: '主要问题线索' },
          { fieldName: 'petition_code', comment: '信访编码' },
          // 受理信息
          { fieldName: 'accept_clue_code', comment: '受理线索编码' },
          { fieldName: 'accept_person_code', comment: '受理人员编码' },
          { fieldName: 'disposal_clue_code', comment: '处置线索编码' },
          { fieldName: 'disposal_person_code', comment: '处置人员编码' },
          // 对象信息
          { fieldName: 'is_national_supervision_object', comment: '是否国家监察对象' },
          { fieldName: 'recover_economic_loss', comment: '挽回经济损失（万元）' },
          { fieldName: 'recovery_amount', comment: '收缴金额（万元）' },
          { fieldName: 'confiscation_amount', comment: '没收金额' },
          { fieldName: 'order_refund_amount', comment: '责令退赔金额' },
          { fieldName: 'register_submit_amount', comment: '登记上交金额' },
          { fieldName: 'recover_loss_due_to_misconduct', comment: '追缴失职渎职滥用职权造成的损失金额' },
          { fieldName: 'remarks', comment: '备注' },
          // 个人信息
          { fieldName: 'ethnicity', comment: '民族' },
          { fieldName: 'birth_date', comment: '出生年月' },
          { fieldName: 'npc_member', comment: '人大代表' },
          { fieldName: 'cppcc_member', comment: '政协委员' },
          { fieldName: 'is_discipline_inspection_official', comment: '是否纪检监察干部' },
          { fieldName: 'disposal_report', comment: '处置情况报告' },
          { fieldName: 'party_join_date', comment: '入党时间' },
          { fieldName: 'cadre_management_authority', comment: '干部管理权限' },
          { fieldName: 'central_managed_cadre_level2', comment: '中管干部二级' },
          // { fieldName: 'id_number', comment: '身份证号' },
          // 时间信息
          { fieldName: 'accept_time', comment: '受理时间' },
          { fieldName: 'accept_stat_time', comment: '受理统计时间' },
          // 处置方式（8种）
          { fieldName: 'disposal_method1_approval_time', comment: '处置方式1批准时间' },
          { fieldName: 'disposal_method1_stat_time', comment: '处置方式1统计时间' },
          { fieldName: 'disposal_method1_level1', comment: '处置方式1一级' },
          { fieldName: 'disposal_method1_level2', comment: '处置方式1二级' },
          { fieldName: 'disposal_method2_approval_time', comment: '处置方式2批准时间' },
          { fieldName: 'disposal_method2_stat_time', comment: '处置方式2统计时间' },
          { fieldName: 'disposal_method2_level1', comment: '处置方式2一级' },
          { fieldName: 'disposal_method2_level2', comment: '处置方式2二级' },
          { fieldName: 'disposal_method3_approval_time', comment: '处置方式3批准时间' },
          { fieldName: 'disposal_method3_stat_time', comment: '处置方式3统计时间' },
          { fieldName: 'disposal_method3_level1', comment: '处置方式3一级' },
          { fieldName: 'disposal_method3_level2', comment: '处置方式3二级' },
          { fieldName: 'disposal_method4_approval_time', comment: '处置方式4批准时间' },
          { fieldName: 'disposal_method4_stat_time', comment: '处置方式4统计时间' },
          { fieldName: 'disposal_method4_level1', comment: '处置方式4一级' },
          { fieldName: 'disposal_method4_level2', comment: '处置方式4二级' },
          { fieldName: 'disposal_method5_approval_time', comment: '处置方式5批准时间' },
          { fieldName: 'disposal_method5_stat_time', comment: '处置方式5统计时间' },
          { fieldName: 'disposal_method5_level1', comment: '处置方式5一级' },
          { fieldName: 'disposal_method5_level2', comment: '处置方式5二级' },
          { fieldName: 'disposal_method6_approval_time', comment: '处置方式6批准时间' },
          { fieldName: 'disposal_method6_stat_time', comment: '处置方式6统计时间' },
          { fieldName: 'disposal_method6_level1', comment: '处置方式6一级' },
          { fieldName: 'disposal_method6_level2', comment: '处置方式6二级' },
          { fieldName: 'disposal_method7_approval_time', comment: '处置方式7批准时间' },
          { fieldName: 'disposal_method7_stat_time', comment: '处置方式7统计时间' },
          { fieldName: 'disposal_method7_level1', comment: '处置方式7一级' },
          { fieldName: 'disposal_method7_level2', comment: '处置方式7二级' },
          { fieldName: 'disposal_method8_approval_time', comment: '处置方式8批准时间' },
          { fieldName: 'disposal_method8_stat_time', comment: '处置方式8统计时间' },
          { fieldName: 'disposal_method8_level1', comment: '处置方式8一级' },
          { fieldName: 'disposal_method8_level2', comment: '处置方式8二级' },
          // 线索来源
          { fieldName: 'clue_source', comment: '线索来源' },
          { fieldName: 'inspection_found_level2', comment: '巡视巡察中发现二级分类' },
          { fieldName: 'superior_assigned_level2', comment: '上级交办转办二级分类' },
          { fieldName: 'is_verified_with_person', comment: '是否与本人核实' },
          { fieldName: 'is_voluntary_confession', comment: '是否主动交代问题' },
          { fieldName: 'is_explained_in_meeting', comment: '是否在民主生活会上作说明' },
          // 办理结果
          { fieldName: 'handling_result', comment: '办理结果' },
          { fieldName: 'closing_time', comment: '办结时间' },
          { fieldName: 'closing_stat_time', comment: '办结统计时间' },
          // 身份分类
          { fieldName: 'is_party_member', comment: '是否党员' },
          { fieldName: 'supervision_object_level2', comment: '监察对象二级分类' },
          { fieldName: 'is_non_party_non_supervision', comment: '是否非党员非监察对象' },
          { fieldName: 'non_party_non_supervision_level2', comment: '非党员非监察对象二级分类' },
          // 行为分类
          { fieldName: 'disciplinary_violation', comment: '违纪行为' },
          { fieldName: 'duty_illegal_crime', comment: '职务违法犯罪行为' },
          { fieldName: 'other_illegal_crime', comment: '其他违法犯罪行为' },
          // 组织措施
          { fieldName: 'organizational_measures', comment: '组织措施' },
          { fieldName: 'organizational_measures_stat_time', comment: '组织措施统计时间' },
          { fieldName: 'is_voluntary_surrender', comment: '是否主动投案' },
          { fieldName: 'is_report_to_superior', comment: '是否属于向上级报告范围' },
          // 调查措施
          { fieldName: 'tech_investigation_measure_count', comment: '技术调查措施使用次数' },
          { fieldName: 'exit_restriction_measure_count', comment: '限制出境措施使用次数' },
          { fieldName: 'tech_investigation_doc_number', comment: '技术调查措施文书编号' },
          { fieldName: 'exit_restriction_doc_number', comment: '限制出境措施文书编号' },
          { fieldName: 'measure_stat_time', comment: '使用措施统计时间' },
          // 办理环节
          { fieldName: 'transfer_to_handling', comment: '转入办理环节' },
          { fieldName: 'transfer_department_name', comment: '移交其他部门办理-部门名称' },
          // 违纪违法行为时间
          { fieldName: 'violation_occurrence_time', comment: '违纪违法行为发生时间' },
          // 纪检监察建议（8条）
          { fieldName: 'suggesting_agency1', comment: '提出建议的纪检监察机构名称1' },
          { fieldName: 'suggested_unit1', comment: '被建议的单位（组织）名称1' },
          { fieldName: 'suggestion_type1', comment: '建议类型1' },
          { fieldName: 'suggestion_content1', comment: '建议文书内容1' },
          { fieldName: 'suggestion_time1', comment: '提出建议时间1' },
          { fieldName: 'suggestion_stat_time1', comment: '提出建议统计时间1' },
          { fieldName: 'suggesting_agency2', comment: '提出建议的纪检监察机构名称2' },
          { fieldName: 'suggested_unit2', comment: '被建议的单位（组织）名称2' },
          { fieldName: 'suggestion_type2', comment: '建议类型2' },
          { fieldName: 'suggestion_content2', comment: '建议文书内容2' },
          { fieldName: 'suggestion_time2', comment: '提出建议时间2' },
          { fieldName: 'suggestion_stat_time2', comment: '提出建议统计时间2' },
          { fieldName: 'suggesting_agency3', comment: '提出建议的纪检监察机构名称3' },
          { fieldName: 'suggested_unit3', comment: '被建议的单位（组织）名称3' },
          { fieldName: 'suggestion_type3', comment: '建议类型3' },
          { fieldName: 'suggestion_content3', comment: '建议文书内容3' },
          { fieldName: 'suggestion_time3', comment: '提出建议时间3' },
          { fieldName: 'suggestion_stat_time3', comment: '提出建议统计时间3' },
          { fieldName: 'suggesting_agency4', comment: '提出建议的纪检监察机构名称4' },
          { fieldName: 'suggested_unit4', comment: '被建议的单位（组织）名称4' },
          { fieldName: 'suggestion_type4', comment: '建议类型4' },
          { fieldName: 'suggestion_content4', comment: '建议文书内容4' },
          { fieldName: 'suggestion_time4', comment: '提出建议时间4' },
          { fieldName: 'suggestion_stat_time4', comment: '提出建议统计时间4' },
          { fieldName: 'suggesting_agency5', comment: '提出建议的纪检监察机构名称5' },
          { fieldName: 'suggested_unit5', comment: '被建议的单位（组织）名称5' },
          { fieldName: 'suggestion_type5', comment: '建议类型5' },
          { fieldName: 'suggestion_content5', comment: '建议文书内容5' },
          { fieldName: 'suggestion_time5', comment: '提出建议时间5' },
          { fieldName: 'suggestion_stat_time5', comment: '提出建议统计时间5' },
          { fieldName: 'suggesting_agency6', comment: '提出建议的纪检监察机构名称6' },
          { fieldName: 'suggested_unit6', comment: '被建议的单位（组织）名称6' },
          { fieldName: 'suggestion_type6', comment: '建议类型6' },
          { fieldName: 'suggestion_content6', comment: '建议文书内容6' },
          { fieldName: 'suggestion_time6', comment: '提出建议时间6' },
          { fieldName: 'suggestion_stat_time6', comment: '提出建议统计时间6' },
          { fieldName: 'suggesting_agency7', comment: '提出建议的纪检监察机构名称7' },
          { fieldName: 'suggested_unit7', comment: '被建议的单位（组织）名称7' },
          { fieldName: 'suggestion_type7', comment: '建议类型7' },
          { fieldName: 'suggestion_content7', comment: '建议文书内容7' },
          { fieldName: 'suggestion_time7', comment: '提出建议时间7' },
          { fieldName: 'suggestion_stat_time7', comment: '提出建议统计时间7' },
          { fieldName: 'suggesting_agency8', comment: '提出建议的纪检监察机构名称8' },
          { fieldName: 'suggested_unit8', comment: '被建议的单位（组织）名称8' },
          { fieldName: 'suggestion_type8', comment: '建议类型8' },
          { fieldName: 'suggestion_content8', comment: '建议文书内容8' },
          { fieldName: 'suggestion_time8', comment: '提出建议时间8' },
          { fieldName: 'suggestion_stat_time8', comment: '提出建议统计时间8' },
          { fieldName: 'impact_end_date', comment: '影响期限结束时间' },
          // 时间统计
          { fieldName: 'handling_time', comment: '办理时间' },
          { fieldName: 'handling_stat_time', comment: '办理统计时间' },
          { fieldName: 'remarks_stat_time', comment: '备注统计时间' },
          // 涉外信息
          { fieldName: 'foreign_related_category', comment: '涉外类别' },
          { fieldName: 'involved_country', comment: '涉及国家（地区）' },
          { fieldName: 'foreign_related_stat_time', comment: '涉外统计时间' },
          { fieldName: 'foreign_related_summary', comment: '涉外信息摘要' },
          // 四种形态
          { fieldName: 'four_forms_situation', comment: '四种形态情形' },
          { fieldName: 'four_forms_stat_time', comment: '四种形态统计时间' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'discipline_organization_punishment': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'report_unit_name', comment: '填报单位名称' },
          { fieldName: 'report_unit_code', comment: '填报单位代码' },
          { fieldName: 'investigated_person', comment: '被调查人' },
          { fieldName: 'work_unit_and_position', comment: '工作单位及职务' },
          { fieldName: 'rank', comment: '职级' },
          { fieldName: 'cadre_management_authority', comment: '干部管理权限' },
          { fieldName: 'central_managed_cadre_level2', comment: '中管干部二级' },
          { fieldName: 'is_unit_or_accident', comment: '是否单位或事故' },
          // 案件信息
          { fieldName: 'case_code', comment: '案件编码' },
          { fieldName: 'involved_person_code', comment: '涉案人员编码' },
          // 个人信息
          { fieldName: 'id_type', comment: '证件类型' },
          { fieldName: 'id_number', comment: '证件号码' },
          { fieldName: 'gender', comment: '性别' },
          { fieldName: 'age', comment: '年龄' },
          { fieldName: 'birth_date', comment: '出生年月' },
          { fieldName: 'education', comment: '学历' },
          { fieldName: 'ethnicity', comment: '民族' },
          { fieldName: 'is_national_supervision_object', comment: '是否国家监察对象' },
          { fieldName: 'national_supervision_object_detail', comment: '国家监察对象详情' },
          { fieldName: 'is_ccp_member', comment: '是否中共党员' },
          { fieldName: 'ccp_congress_representative', comment: '中共党代表' },
          { fieldName: 'party_join_date', comment: '入党时间' },
          { fieldName: 'non_party_non_supervision', comment: '非党员非监察对象' },
          { fieldName: 'non_party_non_supervision_detail', comment: '非党员非监察对象详情' },
          { fieldName: 'npc_member', comment: '人大代表' },
          { fieldName: 'cppcc_member', comment: '政协委员' },
          { fieldName: 'is_discipline_inspection_official', comment: '是否纪检监察干部' },
          { fieldName: 'discipline_inspection_committee', comment: '纪委委员' },
          { fieldName: 'party_committee', comment: '党委委员' },
          { fieldName: 'current_position_start_date', comment: '任现职时间' },
          { fieldName: 'principal_violation', comment: '一把手违纪违法' },
          { fieldName: 'principal_detail1', comment: '一把手细节' },
          { fieldName: 'principal_detail2', comment: '一把手细节2' },
          { fieldName: 'principal_rank', comment: '正副职级' },
          { fieldName: 'department_category', comment: '部门分类' },
          { fieldName: 'department_category1', comment: '部门分类1' },
          { fieldName: 'enterprise_nature', comment: '企业性质' },
          { fieldName: 'enterprise_nature1', comment: '企业性质1' },
          { fieldName: 'enterprise_personnel_category', comment: '企业人员类别' },
          { fieldName: 'enterprise_position', comment: '企业岗位' },
          { fieldName: 'impact_end_date', comment: '影响期限结束时间' },
          // 金额信息
          { fieldName: 'misconduct_amount', comment: '失职渎职金额' },
          { fieldName: 'total_violation_amount', comment: '违纪违法总金额（万元）' },
          // 立案信息
          { fieldName: 'filing_stat_time', comment: '立案统计时间' },
          { fieldName: 'filing_time', comment: '立案时间' },
          { fieldName: 'case_source', comment: '案件来源' },
          { fieldName: 'inspection_found_level2', comment: '巡视巡察中发现二级分类' },
          { fieldName: 'superior_assigned_level2', comment: '上级交办转办二级分类' },
          { fieldName: 'discipline_filing_agency', comment: '纪委立案机关' },
          { fieldName: 'discipline_filing_time', comment: '纪委立案时间' },
          { fieldName: 'discipline_filing_stat_time', comment: '纪委立案统计时间' },
          { fieldName: 'supervision_filing_agency', comment: '监委立案机关' },
          { fieldName: 'supervision_filing_time', comment: '监委立案时间' },
          { fieldName: 'supervision_filing_stat_time', comment: '监委立案统计时间' },
          { fieldName: 'is_transferred_after_filing', comment: '是否其他纪检监察机关立案后移送' },
          { fieldName: 'transfer_method', comment: '立案后移送方式' },
          { fieldName: 'transfer_unit', comment: '移送单位' },
          { fieldName: 'brief_case_description', comment: '简要案情' },
          { fieldName: 'filing_report', comment: '立案报告' },
          { fieldName: 'filing_decision', comment: '立案决定书' },
          { fieldName: 'remarks', comment: '备注' },
          // 特征信息
          { fieldName: 'is_violate_central_regulations', comment: '是否违反中央八项规定精神' },
          { fieldName: 'is_accountability_case', comment: '是否属于问责' },
          { fieldName: 'is_voluntary_confession', comment: '是否主动交代问题' },
          // 结案信息
          { fieldName: 'closing_stat_time', comment: '结案统计时间' },
          { fieldName: 'case_cancellation_time', comment: '销案时间' },
          { fieldName: 'closing_time', comment: '结案时间' },
          // 处分信息
          { fieldName: 'party_discipline_punishment', comment: '党纪处分' },
          { fieldName: 'is_should_dismiss_but_given_warning', comment: '是否本应撤销党内职务但给予严重警告' },
          { fieldName: 'party_punishment_stat_time', comment: '党纪处分统计时间' },
          { fieldName: 'administrative_punishment', comment: '政务处分' },
          { fieldName: 'admin_punishment_stat_time', comment: '政务处分统计时间' },
          { fieldName: 'other_treatment', comment: '其他处理' },
          { fieldName: 'other_treatment_stat_time', comment: '其他处理统计时间' },
          // 司法处理
          { fieldName: 'transfer_prosecution_time', comment: '移送检察机关时间' },
          { fieldName: 'transfer_prosecution_stat_time', comment: '移送检察机关统计时间' },
          { fieldName: 'criminal_punishment_main', comment: '刑事处理主刑' },
          { fieldName: 'criminal_punishment_additional', comment: '刑事处理附加刑' },
          { fieldName: 'main_sentence_years', comment: '主刑年数' },
          { fieldName: 'main_sentence_months', comment: '主刑月数' },
          { fieldName: 'probation_years', comment: '缓刑年数' },
          { fieldName: 'probation_months', comment: '缓刑月数' },
          { fieldName: 'court_judgment_stat_time', comment: '审判机关判决统计时间' },
          // 经济处理
          { fieldName: 'recover_economic_loss', comment: '挽回经济损失（万元）' },
          { fieldName: 'recovery_amount', comment: '收缴金额（万元）' },
          { fieldName: 'confiscation_amount', comment: '没收金额' },
          { fieldName: 'order_refund_amount', comment: '责令退赔金额' },
          { fieldName: 'register_submit_amount', comment: '登记上交金额' },
          { fieldName: 'recover_loss_due_to_misconduct', comment: '追缴失职渎职滥用职权造成的损失金额' },
          // 时间信息
          { fieldName: 'first_violation_time', comment: '首次违纪违法时间' },
          { fieldName: 'last_violation_time', comment: '末次违纪违法时间' },
          { fieldName: 'other_violation_time', comment: '其他违纪违法时间' },
          { fieldName: 'escape_time', comment: '潜逃时间' },
          { fieldName: 'escape_stat_time', comment: '潜逃统计时间' },
          // 审理信息
          { fieldName: 'trial_accept_time', comment: '审理受理时间' },
          { fieldName: 'trial_accept_stat_time', comment: '审理受理统计时间' },
          { fieldName: 'trial_agency', comment: '审理机关' },
          { fieldName: 'trial_completion_time', comment: '审结时间' },
          { fieldName: 'trial_completion_stat_time', comment: '审结统计时间' },
          { fieldName: 'punishment_decision', comment: '处分决定' },
          { fieldName: 'court_judgment_time', comment: '审判机关判决时间' },
          { fieldName: 'judicial_judgment_amount', comment: '司法判决金额（万元）' },
          // 报告文件
          { fieldName: 'investigation_report', comment: '审查调查报告' },
          { fieldName: 'trial_report', comment: '审理报告' },
          { fieldName: 'case_analysis', comment: '案件剖析' },
          // 其他处分信息
          { fieldName: 'probation_period_years', comment: '留党察看年限' },
          { fieldName: 'enterprise_level', comment: '企业级别' },
          { fieldName: 'escape_destination', comment: '潜逃去向' },
          { fieldName: 'escape_destination_detail', comment: '潜逃去向细节' },
          // 调查信息
          { fieldName: 'investigation_suspension_time', comment: '调查中止时间' },
          { fieldName: 'investigation_suspension_stat_time', comment: '调查中止统计时间' },
          { fieldName: 'capture_time', comment: '抓获时间' },
          { fieldName: 'capture_stat_time', comment: '抓获统计时间' },
          { fieldName: 'case_analysis_report_stat_time', comment: '案件剖析报告统计时间' },
          // 行为分类
          { fieldName: 'disciplinary_violation', comment: '违纪行为' },
          { fieldName: 'duty_illegal_crime', comment: '职务违法犯罪行为' },
          { fieldName: 'other_illegal_crime', comment: '其他违法犯罪行为' },
          // 措施信息
          { fieldName: 'measure_agency', comment: '采取措施机关' },
          { fieldName: 'measure_agency_name', comment: '采取措施机关名称' },
          { fieldName: 'detention_start_time', comment: '留置起始时间' },
          { fieldName: 'detention_start_stat_time', comment: '留置起始统计时间' },
          { fieldName: 'measure_location', comment: '采取措施地点' },
          { fieldName: 'measure_location_category', comment: '采取措施地点分类' },
          { fieldName: 'detention_decision', comment: '留置决定书' },
          { fieldName: 'detention_end_time', comment: '留置结束时间' },
          { fieldName: 'detention_end_stat_time', comment: '留置结束统计时间' },
          { fieldName: 'detention_days', comment: '留置天数' },
          { fieldName: 'is_extension', comment: '是否延期' },
          { fieldName: 'extension_days', comment: '延期天数' },
          { fieldName: 'extended_detention_decision', comment: '延长留置时间决定书' },
          // 特征分类
          { fieldName: 'is_masses_problem', comment: '是否群众身边的不正之风和腐败问题' },
          // 组织措施
          { fieldName: 'organizational_measures', comment: '组织措施' },
          { fieldName: 'organizational_measures_stat_time', comment: '组织措施统计时间' },
          // 其他金额
          { fieldName: 'transfer_prosecution_amount', comment: '移送检察机关金额（万元）' },
          // 历史措施
          { fieldName: 'shuanggui_start_time', comment: '两规两指起始时间' },
          { fieldName: 'shuanggui_stat_time', comment: '两规两指统计时间' },
          { fieldName: 'shuanggui_end_time', comment: '两规两指解除时间' },
          { fieldName: 'shuanggui_end_stat_time', comment: '两规两指解除统计时间' },
          // 忏悔材料
          { fieldName: 'confession', comment: '忏悔书' },
          // 投案信息
          { fieldName: 'is_voluntary_surrender', comment: '是否主动投案' },
          { fieldName: 'is_report_to_superior', comment: '是否属于向上级纪委监委报告范围' },
          // 补充调查
          { fieldName: 'is_return_supplementary_investigation', comment: '是否退回补充调查' },
          { fieldName: 'return_supplementary_time', comment: '退回补充调查时间' },
          { fieldName: 'return_supplementary_stat_time', comment: '退回补充调查统计时间' },
          { fieldName: 'return_supplementary_reason', comment: '退回补充调查原因' },
          { fieldName: 'is_second_return_supplementary', comment: '是否二次退回补充调查' },
          { fieldName: 'second_return_supplementary_time', comment: '二次退回补充调查时间' },
          { fieldName: 'second_return_supplementary_stat_time', comment: '二次退回补充调查统计时间' },
          { fieldName: 'second_return_supplementary_reason', comment: '二次退回补充调查原因' },
          // 不起诉信息
          { fieldName: 'is_no_prosecution', comment: '是否不起诉' },
          { fieldName: 'no_prosecution_reason', comment: '不起诉原因' },
          { fieldName: 'no_prosecution_decision_time', comment: '决定不起诉时间' },
          { fieldName: 'no_prosecution_decision_stat_time', comment: '决定不起诉统计时间' },
          // 司法信息
          { fieldName: 'court_judgment_crime', comment: '审判机关判决罪名' },
          { fieldName: 'public_security_punishment', comment: '公安等其他行政法机关处罚' },
          { fieldName: 'public_security_punishment_detail', comment: '公安等其他行政法机关处罚详细内容' },
          { fieldName: 'transfer_public_security_time', comment: '移送公安机关时间' },
          { fieldName: 'transfer_public_security_stat_time', comment: '移送公安机关统计时间' },
          { fieldName: 'public_security_punishment_time', comment: '公安等其他行政法机关处罚时间' },
          { fieldName: 'public_security_punishment_stat_time', comment: '公安等其他行政法机关处罚统计时间' },
          // 处分变更
          { fieldName: 'change_punishment_time', comment: '变更处分时间' },
          { fieldName: 'revoke_punishment_time', comment: '撤销处分时间' },
          { fieldName: 'change_punishment_stat_time', comment: '变更处分统计时间' },
          { fieldName: 'revoke_punishment_stat_time', comment: '撤销处分统计时间' },
          { fieldName: 'change_revoke_reason', comment: '变更撤销原因' },
          { fieldName: 'new_party_punishment', comment: '新党纪处分' },
          { fieldName: 'is_new_should_dismiss_but_warning', comment: '新党纪处分是否属于"本应撤销党内职务但给予严重警告"' },
          { fieldName: 'new_probation_period_years', comment: '新留党察看年限' },
          { fieldName: 'new_administrative_punishment', comment: '新政务处分' },
          { fieldName: 'new_other_treatment', comment: '新其他处理' },
          { fieldName: 'new_organizational_measures', comment: '新组织措施' },
          // 从宽处罚建议
          { fieldName: 'is_leniency_suggestion', comment: '监察机关是否提出从宽处罚建议' },
          { fieldName: 'leniency_suggestion_type', comment: '从宽处罚建议类型' },
          { fieldName: 'leniency_suggestion_situation', comment: '监察机关提出从宽处罚建议的情形' },
          { fieldName: 'leniency_suggestion_stat_time', comment: '提出从宽处罚建议统计时间' },
          { fieldName: 'is_prosecution_adopt_leniency', comment: '检察机关是否采纳从宽处罚建议' },
          { fieldName: 'prosecution_adopt_leniency_time', comment: '检察机关采纳从宽处罚建议时间' },
          { fieldName: 'prosecution_adopt_leniency_stat_time', comment: '检察机关采纳从宽处罚建议统计时间' },
          { fieldName: 'is_court_adopt_leniency', comment: '审判机关是否采纳从宽处罚建议' },
          { fieldName: 'court_adopt_leniency_time', comment: '审判机关采纳从宽处罚建议时间' },
          { fieldName: 'court_adopt_leniency_stat_time', comment: '审判机关采纳从宽处罚建议统计时间' },
          // 法律文书
          { fieldName: 'prosecution_transfer_opinion', comment: '纪检监察机关移送检察机关起诉意见书' },
          // 调查措施使用次数
          { fieldName: 'freeze_measure_count', comment: '冻结措施使用次数' },
          { fieldName: 'search_measure_count', comment: '搜查措施使用次数' },
          { fieldName: 'seizure_measure_count', comment: '查封使用次数' },
          { fieldName: 'control_measure_count', comment: '扣押使用次数' },
          { fieldName: 'tech_investigation_count', comment: '技术调查使用次数' },
          { fieldName: 'wanted_count', comment: '通缉使用次数' },
          { fieldName: 'exit_restriction_count', comment: '限制出境使用次数' },
          // 措施使用情况
          { fieldName: 'freeze_measure_situation', comment: '冻结措施使用情况' },
          { fieldName: 'search_measure_situation', comment: '搜查措施使用情况' },
          { fieldName: 'seizure_measure_situation', comment: '查封措施使用情况' },
          { fieldName: 'control_measure_situation', comment: '扣押措施使用情况' },
          { fieldName: 'tech_investigation_situation', comment: '技术调查措施使用情况' },
          { fieldName: 'wanted_measure_situation', comment: '通缉措施使用情况' },
          { fieldName: 'exit_restriction_situation', comment: '限制出境措施使用情况' },
          // 统计时间
          { fieldName: 'measure_usage_stat_time', comment: '使用措施统计时间' },
          { fieldName: 'remarks_stat_time', comment: '备注统计时间' },
          // 纪检监察建议（8条）
          { fieldName: 'suggesting_agency1', comment: '提出建议的纪检监察机构名称1' },
          { fieldName: 'suggested_unit1', comment: '被建议的单位（组织）名称1' },
          { fieldName: 'suggestion_type1', comment: '建议类型1' },
          { fieldName: 'suggestion_content1', comment: '建议文书内容1' },
          { fieldName: 'suggestion_time1', comment: '提出建议时间1' },
          { fieldName: 'suggestion_stat_time1', comment: '提出建议统计时间1' },
          { fieldName: 'suggesting_agency2', comment: '提出建议的纪检监察机构名称2' },
          { fieldName: 'suggested_unit2', comment: '被建议的单位（组织）名称2' },
          { fieldName: 'suggestion_type2', comment: '建议类型2' },
          { fieldName: 'suggestion_content2', comment: '建议文书内容2' },
          { fieldName: 'suggestion_time2', comment: '提出建议时间2' },
          { fieldName: 'suggestion_stat_time2', comment: '提出建议统计时间2' },
          { fieldName: 'suggesting_agency3', comment: '提出建议的纪检监察机构名称3' },
          { fieldName: 'suggested_unit3', comment: '被建议的单位（组织）名称3' },
          { fieldName: 'suggestion_type3', comment: '建议类型3' },
          { fieldName: 'suggestion_content3', comment: '建议文书内容3' },
          { fieldName: 'suggestion_time3', comment: '提出建议时间3' },
          { fieldName: 'suggestion_stat_time3', comment: '提出建议统计时间3' },
          { fieldName: 'suggesting_agency4', comment: '提出建议的纪检监察机构名称4' },
          { fieldName: 'suggested_unit4', comment: '被建议的单位（组织）名称4' },
          { fieldName: 'suggestion_type4', comment: '建议类型4' },
          { fieldName: 'suggestion_content4', comment: '建议文书内容4' },
          { fieldName: 'suggestion_time4', comment: '提出建议时间4' },
          { fieldName: 'suggestion_stat_time4', comment: '提出建议统计时间4' },
          { fieldName: 'suggesting_agency5', comment: '提出建议的纪检监察机构名称5' },
          { fieldName: 'suggested_unit5', comment: '被建议的单位（组织）名称5' },
          { fieldName: 'suggestion_type5', comment: '建议类型5' },
          { fieldName: 'suggestion_content5', comment: '建议文书内容5' },
          { fieldName: 'suggestion_time5', comment: '提出建议时间5' },
          { fieldName: 'suggestion_stat_time5', comment: '提出建议统计时间5' },
          { fieldName: 'suggesting_agency6', comment: '提出建议的纪检监察机构名称6' },
          { fieldName: 'suggested_unit6', comment: '被建议的单位（组织）名称6' },
          { fieldName: 'suggestion_type6', comment: '建议类型6' },
          { fieldName: 'suggestion_content6', comment: '建议文书内容6' },
          { fieldName: 'suggestion_time6', comment: '提出建议时间6' },
          { fieldName: 'suggestion_stat_time6', comment: '提出建议统计时间6' },
          { fieldName: 'suggesting_agency7', comment: '提出建议的纪检监察机构名称7' },
          { fieldName: 'suggested_unit7', comment: '被建议的单位（组织）名称7' },
          { fieldName: 'suggestion_type7', comment: '建议类型7' },
          { fieldName: 'suggestion_content7', comment: '建议文书内容7' },
          { fieldName: 'suggestion_time7', comment: '提出建议时间7' },
          { fieldName: 'suggestion_stat_time7', comment: '提出建议统计时间7' },
          { fieldName: 'suggesting_agency8', comment: '提出建议的纪检监察机构名称8' },
          { fieldName: 'suggested_unit8', comment: '被建议的单位（组织）名称8' },
          { fieldName: 'suggestion_type8', comment: '建议类型8' },
          { fieldName: 'suggestion_content8', comment: '建议文书内容8' },
          { fieldName: 'suggestion_time8', comment: '提出建议时间8' },
          { fieldName: 'suggestion_stat_time8', comment: '提出建议统计时间8' },
          // 涉外信息
          { fieldName: 'foreign_related_category', comment: '涉外类别' },
          { fieldName: 'involved_country', comment: '涉及国家（地区）' },
          { fieldName: 'foreign_related_stat_time', comment: '涉外统计时间' },
          { fieldName: 'foreign_related_summary', comment: '涉外信息摘要' },
          // 其他信息
          { fieldName: 'unrecovered_overseas_assets', comment: '尚未追回的境外涉案财物' },
          { fieldName: 'is_self_handled_case', comment: '纪检监察机关自办案件' },
          { fieldName: 'is_public_security_transferred_case', comment: '公检法等机关移送的非职务违法犯罪等案件' },
          { fieldName: 'public_security_transferred_detail', comment: '公检法等机关移送的非职务违法犯罪等案件二级分类' },
          { fieldName: 'detention_object_identity', comment: '留置对象身份' },
          { fieldName: 'corruption_bribery_time', comment: '贪污贿赂行为发生时间' },
          { fieldName: 'corruption_bribery_first_year', comment: '贪污贿赂行为的首次年份' },

          { fieldName: 'duty_ethics_reply_time', comment: '党风廉政意见回复时间' },
{ fieldName: 'duty_ethics_reply_type', comment: '党风廉政意见回复类型' },
{ fieldName: 'duty_ethics_reply_person_count', comment: '党风廉政意见回复涉及人次' },
{ fieldName: 'duty_ethics_reply_materials', comment: '党风廉政意见回复材料' },

{ fieldName: 'false_report_handle_time', comment: '不如实报告处理时间' },
{ fieldName: 'false_report_issue', comment: '不如实报告问题' },
{ fieldName: 'false_report_disposal', comment: '不如实报告处理情况' },
{ fieldName: 'false_report_punishment_no', comment: '不如实报告处分文号' },
{ fieldName: 'false_report_remarks', comment: '不如实报告备注' },

{ fieldName: 'other_integrity_material_time', comment: '其他廉政材料时间' },
{ fieldName: 'other_integrity_material_name', comment: '其他廉政材料名称' },
{ fieldName: 'other_integrity_material_content', comment: '其他廉政材料内容' },
{ fieldName: 'other_integrity_material_department', comment: '其他廉政材料形成部门' },
{ fieldName: 'other_integrity_material_remarks', comment: '其他廉政材料备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'personal_matters_report_punishment': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'problem_description', comment: '问题' },
          { fieldName: 'handling_situation', comment: '处理情况' },
          { fieldName: 'punishment_document_number', comment: '处分文号' },
          { fieldName: 'remarks', comment: '备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'party_conduct_opinion_reply': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'type', comment: '类型' },
          { fieldName: 'person_count', comment: '人次' },
          { fieldName: 'reply_document', comment: '回复材料' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ],
        'other_clean_government_materials': [
          // { fieldName: 'id', comment: 'ID' },
          // 基本信息
          { fieldName: 'time_period', comment: '时间' },
          { fieldName: 'material_name', comment: '材料名称' },
          { fieldName: 'material_content', comment: '材料内容' },
          { fieldName: 'material_forming_department', comment: '材料形成部门' },
          { fieldName: 'remarks', comment: '备注' },
          // 系统字段
          // { fieldName: 'created_at', comment: '创建时间' },
          // { fieldName: 'updated_at', comment: '更新时间' }
        ]
      };
      
      const columns = tableColumns[table.table_name] || [];
      
      return {
        name: table.table_name,
        columns: columns,
        selectedColumns: table.columns ? table.columns.split(',') : [],
        key: table.table_name
      };
    });
    
    return {
      ...exportData,
      viewableUnits: viewableUnits.map(unit => unit.value), // 只需要value
      displayUnits: viewableUnits, // 完整单位信息用于显示
      viewableTables: viewableTables,
      units: exportData.units // 保留原始units字段
    };
  } catch (error) {
    console.error('获取导出配置失败:', error);
    throw error;
  }
}

// 查询export表数据
const getExportConfigs = async (queryParams) => {
  try {
    // 构建查询条件
    let whereClause = '';
    let whereParams = [];
    
    if (queryParams.groupName) {
      whereClause = 'WHERE export_name LIKE ?';
      whereParams.push(`%${queryParams.groupName}%`);
    }
    
    // 查询总记录数
    const countResult = await database.query(
      `SELECT COUNT(*) as total FROM export ${whereClause}`,
      whereParams
    );
    const total = countResult[0].total || 0;
    
    if (total === 0) {
      return { list: [], total: 0 };
    }
    
    // 分页查询数据
    const pageSize = queryParams.pageSize || 10;
    const pageNum = queryParams.pageNum || 1;
    const offset = (pageNum - 1) * pageSize;
    
    const exports = await database.query(
      `SELECT * FROM export ${whereClause} ORDER BY export_name LIMIT ? OFFSET ?`,
      [...whereParams, pageSize, offset]
    );
    
    // 获取所有单位信息（code和name的映射）
    const unitsMap = {};
    const unitsResult = await database.query('SELECT code, name FROM subUnits');
    unitsResult.forEach(unit => {
      unitsMap[unit.code] = unit.name;
    });
    
    // 处理数据，转换units为单位名称
    const resultList = exports.map(item => {
      let viewableUnits = [];
      if (item.units) {
        const unitCodes = item.units.split(',');
        viewableUnits = unitCodes.map(code => unitsMap[code] || code);
      }
      
      return {
        id: item.export_id,
        groupName: item.export_name,
        viewableUnits: viewableUnits,
        units: item.units // 保留原始units字段
      };
    });
    
    return {
      list: resultList,
      total: total
    };
  } catch (error) {
    console.error('获取导出配置失败:', error);
    throw error;
  }
}
import EditDialog from './components/EditDialog.vue'
// import Pagination from '@/components/Pagination/index.vue'
import TopNav from './navmenu.vue'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  groupName: ''
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增分组')
const isEdit = ref(false)
// 使用ref包裹对象，以便完全替换
const form = ref({
  id: null,
  groupName: '',
  viewableUnits: [],
  viewableTables: [] // 新增可查看表数据
})

// 重置表单 - 创建一个全新的表单对象
const resetForm = () => {
  form.value = {
    id: null,
    groupName: '',
    viewableUnits: []
  }
}

// 获取表格数据
const getList = async () => {
  try {
    loading.value = true
    const result = await getExportConfigs(queryParams)
    tableData.value = result.list
    total.value = result.total
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 新增按钮
const handleAdd = () => {
  dialogTitle.value = '新增分组'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    dialogTitle.value = '编辑分组'
    isEdit.value = true
    
    // 获取完整的导出配置数据
    const fullData = await getExportConfigById(row.id)
    
    // 更新表单数据
    form.value = {
      id: fullData.export_id,
      groupName: fullData.export_name,
      viewableUnits: fullData.viewableUnits || [],
      viewableTables: fullData.viewableTables || []
    }
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取编辑数据失败:', error)
    ElMessage.error('获取编辑数据失败: ' + error.message)
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该分组吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 先删除export_subtable表中的数据
      await database.delete(
        'DELETE FROM export_subtable WHERE export_id = ?',
        [row.id]
      );
      
      // 再删除export表中的数据
      await database.delete(
        'DELETE FROM export WHERE export_id = ?',
        [row.id]
      );
      
      ElMessage.success('删除成功')
      getList() // 删除后刷新页面
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + error.message)
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    if (!form.value.groupName.trim()) {
      throw new Error('分组名不能为空')
    }
    if (form.value.viewableUnits.length === 0) {
      throw new Error('请选择至少一个可查看单位')
    }

    // 准备数据
    const unitCodes = form.value.viewableUnits; // 假设viewableUnits存储的是单位code
    
    // 生成export_id
    const exportId = Date.now().toString() + Math.floor(Math.random() * 1000);
    
    // 准备export表数据
    const exportData = {
      export_id: exportId,
      export_name: form.value.groupName,
      units: unitCodes.join(',')
    };
    
    // 插入export表
    await database.insert(
      'INSERT INTO export (export_id, export_name, units) VALUES (?, ?, ?)',
      [exportData.export_id, exportData.export_name, exportData.units]
    );
    
    ElMessage.success(isEdit.value ? '修改成功' : '新增成功');
    dialogVisible.value = false;
    getList();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(`保存失败: ${error.message}`);
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  // 处理多选逻辑
}

// 查看表结构
const handleViewTable = (table) => {
  console.log('查看表结构:', table)
  // 这里可以打开一个模态框显示表结构详情
}

// 初始化加载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.page-container {
  display: flex;
  flex-direction: column;
  height: 98vh;
  background: #f5f6f8;
  overflow: hidden;
}

.app-container {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.mb-20 {
  flex: 1;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  padding: 20px;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-wrapper {
  width: 100%;
  height: calc(100% - 120px);
  margin-top: 20px;
  display: block;
  overflow: auto; /* 改为auto，当内容超过高度时显示滚动条 */
  box-sizing: border-box;
  padding-right: 0;
}

/* 确保el-table不会自动扩展高度 */
:deep(.el-table) {
  width: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table__body-wrapper) {
  flex: 1;
  min-height: 0;
  max-width: 100%;
}

/* 自定义滚动条样式 */
.table-wrapper::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
  transition: background 0.3s ease;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #888;
}
</style>